import React, { createContext, useState, useContext, useEffect } from 'react';
import axios from 'axios';

const AuthContext = createContext();

export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem('token'));
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  // 设置axios默认headers
  useEffect(() => {
    if (token) {
      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
    } else {
      delete axios.defaults.headers.common['Authorization'];
    }
  }, [token]);

  // 加载用户信息
  useEffect(() => {
    const loadUser = async () => {
      if (!token) {
        setLoading(false);
        return;
      }

      try {
        const res = await axios.get('/api/auth/me');
        setUser(res.data);
        setError(null);
      } catch (err) {
        console.error('加载用户信息失败:', err);
        setError('登录已过期，请重新登录');
        logout();
      } finally {
        setLoading(false);
      }
    };

    loadUser();
  }, [token]);

  // 登录方法
  const login = async (username, password) => {
    try {
      setLoading(true);
      const res = await axios.post('/api/auth/login', { username, password });
      
      // 保存token到localStorage和状态
      localStorage.setItem('token', res.data.token);
      setToken(res.data.token);
      setUser(res.data.user);
      setError(null);
      
      return res.data;
    } catch (err) {
      console.error('登录失败:', err);
      setError(err.response?.data?.message || '登录失败，请检查用户名和密码');
      throw err;
    } finally {
      setLoading(false);
    }
  };

  // 注销方法
  const logout = () => {
    localStorage.removeItem('token');
    setToken(null);
    setUser(null);
    setError(null);
  };

  // 注册方法 (仅管理员)
  const register = async (userData) => {
    try {
      setLoading(true);
      const res = await axios.post('/api/auth/register', userData);
      setError(null);
      return res.data;
    } catch (err) {
      console.error('注册失败:', err);
      setError(err.response?.data?.message || '注册失败，请稍后再试');
      throw err;
    } finally {
      setLoading(false);
    }
  };

  // 更新用户信息
  const updateUser = async (userData) => {
    try {
      setLoading(true);
      const res = await axios.put('/api/auth/me', userData);
      setUser(res.data.user);
      setError(null);
      return res.data;
    } catch (err) {
      console.error('更新用户信息失败:', err);
      setError(err.response?.data?.message || '更新用户信息失败');
      throw err;
    } finally {
      setLoading(false);
    }
  };

  // 提供身份验证状态和方法
  const value = {
    user,
    token,
    loading,
    error,
    isAuthenticated: !!user,
    login,
    logout,
    register,
    updateUser,
    clearError: () => setError(null)
  };

  return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}; 